package com.study_day01.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study_day01.entiry.*;
import com.study_day01.mapper.DrugMapper;
import com.study_day01.mapper.OrderMapper;
import com.study_day01.service.CartService;
import com.study_day01.service.DrugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
public class DrugController {

    @Autowired
    private DrugService drugService;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DrugMapper drugMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/drug")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity getDrugModel(@RequestParam(required = false) String drName) {
        List<Drug> drugList;
        String cacheKey = "drugList";
        // 检查 Redis 中是否存在缓存
        Boolean hasKey = redisTemplate.hasKey(cacheKey);
        if (hasKey != null && hasKey) {
            // 如果存在缓存，则从 Redis 中读取并返回
            drugList = (List<Drug>) redisTemplate.opsForValue().get(cacheKey);
        } else {
            // 如果不存在缓存，则从数据库中获取数据
            if (drName != null) {
                // 如果指定了 drName 参数，则按照 drName 进行模糊查询
                drugList = drugService.getDrugsByName(drName);
            } else {
                // 如果没有指定 drName 参数，则获取所有药品
                drugList = drugService.getAllDrugs();
            }
            // 将结果存入 Redis 缓存，设置过期时间为一小时（单位：秒）
            redisTemplate.opsForValue().set(cacheKey, drugList, 3600, TimeUnit.SECONDS);
        }
        return ResponseEntity.ok(drugList);
    }
    @GetMapping("/drugs/{id}")
    public ResponseEntity getDrugById(@PathVariable("id") String id) {

         Drug drug = drugService.getDrugById(Integer.valueOf(id));

        return ResponseEntity.ok(drug);
    }

    @PostMapping("/drug/add-to-cart")
    public ResponseEntity<String> addToCart(@RequestBody AddToCartRequest request) {
        cartService.addToCart(request.getDrId());
        return ResponseEntity.ok("药品已成功添加到购物车！");
    }

    @GetMapping("cart")
    public ResponseEntity<List<CartItem>> viewCart() {
        List<CartItem> cartItems = cartService.getCartItems();
        return ResponseEntity.ok(cartItems);
    }

    @PostMapping("/drug/reduce-to-cart")
    public ResponseEntity<String> removeFromCart(@RequestBody RemoveFromCartRequest request) {
        cartService.removeFromCart(request.getDrId());
        return ResponseEntity.ok("药品已从购物车中移除！");
    }

    @PostMapping("/drug/pay")
    public ResponseEntity<String> pay(@RequestBody Orders orders){
        orderMapper.insert(orders);
        return ResponseEntity.ok("结算成功");
    }
    @GetMapping("/drug/order")
    public ResponseEntity<List> order(){
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.ne("status", 1);
        List<Orders> orders = orderMapper.selectList(null);
        return ResponseEntity.ok(orders);
    }

    @Autowired
    private ServletContext servletContext;
    @PutMapping("/drug/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("recordId") Integer recordId) throws IOException {
        String uploadDirectory="upload/";
        try {
            // 如果文件夹不存在，创建文件夹
            File uploadFolder = new File(uploadDirectory);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdirs();
            }

            // 获取上传文件的原始文件名
            String originalFileName = file.getOriginalFilename();

            // 构建上传文件的路径
            Path path = Paths.get(uploadDirectory, originalFileName);

            // 将上传文件写入到指定路径
            try (InputStream inputStream = file.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(path.toFile())) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            // 更新数据库中记录的图片URL和ID
            Drug drug = new Drug();
            drug.setDrId(recordId);
            drug.setImgUrl(path.toString());
            drugMapper.updateById(drug);

            // 返回成功响应
            return ResponseEntity.ok().body("File uploaded successfully");
        } catch (IOException e) {
            e.printStackTrace();
            // 处理文件上传异常
            return ResponseEntity.badRequest().body("Failed to upload file");
        }
    }

    @PutMapping("/drug/refund")
    public ResponseEntity<String> refund(@RequestBody Orders request){
        request.setStatus(1);
        orderMapper.updateById(request);
        return ResponseEntity.ok("退款成功");
    }
}
